package com.jkdl.springboot.service.impl;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.jkdl.springboot.common.util.JsonResult;
import com.jkdl.springboot.common.util.Md5Util;
import com.jkdl.springboot.common.util.WxUtil.HttpUtil;
import com.jkdl.springboot.common.util.WxUtil.WxConfigUtil;
import com.jkdl.springboot.common.util.WxUtil.WxunionidUtil;
import com.jkdl.springboot.dao.USecondUsersMapper;
import com.jkdl.springboot.dao.USersMapper;
import com.jkdl.springboot.domain.*;
import com.jkdl.springboot.entity.*;
import com.jkdl.springboot.enums.OrderStatus;
import com.jkdl.springboot.exception.BusinessException;
import com.jkdl.springboot.service.USecondUserService;
import com.jkdl.springboot.service.USersService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Service
public class USecondUsermpl implements USecondUserService{

    @Autowired
    private USecondUsersMapper uSecondUsersMapper;

    @Override
    public Map<String, Object> checkoutUserExist(String code) {
        Map<String, String> userInfo = getWxUserInfo(code);
        if (null == userInfo || userInfo.isEmpty()) {
            throw new BusinessException("用户信息查询失败");
        }
        USecondUsersExample userExample = new USecondUsersExample();
        userExample.createCriteria().andOpenidEqualTo(userInfo.get("openid"));
        List<USecondUsers> users = uSecondUsersMapper.selectByExample(userExample);
        Map<String, Object> result = new HashMap<>();
        if (null != users && users.size() > 0) {
            USecondUsers user = users.get(0);
            result.put("isExist", 1);
            result.put("wxUserId", user.getId());
            result.put("openId",userInfo.get("openid"));
            result.put("id",userInfo.get("id"));
            return result;
        } else {
            result.put("isExist", 0);
            result.put("wxUserId", null);
            result.put("openId",userInfo.get("openid"));
            return result;
        }
    }

    @Override
    public int loginAuth(UsersWxVo usersWxVo) throws Exception{
        Map<String, String> map = getWxUserInfo(usersWxVo.getCode());
        System.out.println(usersWxVo.getEncryptedData());
        String wxUserInfo = WxunionidUtil.decrypt2(usersWxVo.getEncryptedData(), map.get("sessionKey"), usersWxVo.getIv(), "UTF-8");
        JSONObject jsonObject = JSON.parseObject(wxUserInfo);
        String unionid = String.valueOf(jsonObject.get("unionId"));

        USecondUsersExample userExample = new USecondUsersExample();
        userExample.createCriteria().andOpenidEqualTo(map.get("openid"));
        List<USecondUsers> users = uSecondUsersMapper.selectByExample(userExample);

        if (null != users && users.size() > 0) {
            USecondUsers user = users.get(0);
            user.setUnionId(unionid);
            user.setNickname(usersWxVo.getNickname());
            user.setHeadimgurl(usersWxVo.getHeadimgurl());

            int result = uSecondUsersMapper.updateByPrimaryKeySelective(user);
            if (1 == result) {
                return user.getId();
            }
        }

        return 0;


    }

    @Override
    public Integer addUser(USecondUserAddVo uSecondUserAddVo) throws Exception {
        Map<String, String> map = getWxUserInfo(uSecondUserAddVo.getCode());
//        String wxUserInfo = WxunionidUtil.decrypt2(uSecondUserAddVo.getEncryptedData(), map.get("sessionKey"), uSecondUserAddVo.getIv(), "UTF-8");
//        JSONObject jsonObject = JSON.parseObject(wxUserInfo);
//        String unionId = String.valueOf(jsonObject.get("unionid"));
        USecondUsers user = new USecondUsers();
        user.setCreatetime(new  Date());
        user.setOpenid(map.get("openid"));
        user.setAmount(0.00);
        user.setQyid(103);
        user.setPassword(Md5Util.getMd5("123456"));

        int i = uSecondUsersMapper.insertSelective(user);
        if (1 == i) {
            return user.getId();
        }
        return null;
    }


    @Override
    public JsonResult uSecondUserList(USecondUserListQueryVo uSecondUserListQueryVo) {
        int pageStart = (uSecondUserListQueryVo.getPageNum()-1)*uSecondUserListQueryVo.getPageSize() ;
        uSecondUserListQueryVo.setPageStart(pageStart);

        List<USecondUsers> uSecondUsersList = uSecondUsersMapper.selectUSecondUserList(uSecondUserListQueryVo);

        PageInfo<USecondUsers> uSecondUsersPageInfo = new PageInfo<>(uSecondUsersList);
        //总条数
        long total = uSecondUsersMapper.selectAllSecondUserCount(uSecondUserListQueryVo);
        log.info("总用户数量:"+ total);

        uSecondUsersPageInfo.setTotal(total);
        return JsonResult.ok(uSecondUsersPageInfo);
    }

    @Override
    public JsonResult updateUSeconsUserSmlock(USecondUserListQueryVo uSecondUserListQueryVo) {
        if(0==uSecondUserListQueryVo.getId()||"".equals(uSecondUserListQueryVo.getId())){
            return JsonResult.build("参数错误");
        }

        USecondUsers uSecondUsers = uSecondUsersMapper.selectByPrimaryKey(uSecondUserListQueryVo.getId());
        if(null==uSecondUsers.getOpenid()){
            return JsonResult.build("用户不存在");
        }

        //是免支付  修改为正常会员
        if(0 == uSecondUserListQueryVo.getSmlock()){
            if(null == uSecondUsers.getSmlock() || 0 == uSecondUsers.getSmlock()){
                uSecondUsers.setSmlock(1);
            }
        }

        //是正常会员  修改为免支付
        if(1 == uSecondUserListQueryVo.getSmlock()){
            if(1 == uSecondUsers.getSmlock()){
                uSecondUsers.setSmlock(0);
            }
        }

        return JsonResult.ok(uSecondUsersMapper.updateByPrimaryKey(uSecondUsers));
    }

    /**
     * @param code 微信用户code
     * @author XOu
     * @description 获取微信用户信息
     * @version 1.0
     * @date 2018/7/1
     * @modified
     */
    public Map<String, String> getWxUserInfo(String code) {
        String openParam = "appid=" + WxConfigUtil.JKDL_APPID + "&secret=" + WxConfigUtil.JKDL_SECRT + "&js_code=" + code + "&grant_type=authorization_code";
        String openJsonStr = HttpUtil.SendGET("https://api.weixin.qq.com/sns/jscode2session", openParam);
        log.info("获取微信用户unionId接口返回参数{}", openJsonStr);

        Map openMap = JSON.parseObject(openJsonStr);
        if (openMap.containsKey("errcode")) {
            log.error("==========调用微信接口异常{}", String.valueOf(openMap.get("errmsg")));
            throw new BusinessException("调用微信接口异常");
        }
        log.info("获取的openid是", openMap.get("openid"));
        String sessionKey = String.valueOf(openMap.get("session_key"));
        String openid = String.valueOf(openMap.get("openid"));
        Map<String, String> resultMap = new HashMap<>();
        resultMap.put("sessionKey", sessionKey);
        resultMap.put("openid", openid);
        return resultMap;
    }
}
